package com.wx.controller;

import com.wx.exception.RequestParamEmptyException;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyControllerAdvice {

	/**
	 * 请求参数转转，测试代码
	 * @see UserController#saveUserAndCat(com.wx.pojo.User, com.wx.pojo.Cat, org.springframework.ui.Model)
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

	/**
	 * 全局属性设置
	 */
	@ModelAttribute
	public void globalAttribute(Model model) {
		model.addAttribute("global", "全局属性");
	}

//	@ModelAttribute
//	public String globalAttribute() {
//		return "全局属性"; //
//	}

	/**
	 * 返回定制的错误请求参数，测试代码
	 * @see AnnotationController#customException(Map, Model)
	 */
	@ExceptionHandler(RequestParamEmptyException.class)
	@ResponseBody
	public Map<String, Object> handleException(Exception e) {
		Map<String, Object> map = new HashMap<>();
		map	.put("code", "user.notExist");
		map	.put("message", e.getMessage());
		return map;
	}
}
